package wifiunion.com.notice.fragment;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aspsine.irecyclerview.IRecyclerView;


import java.util.ArrayList;
import java.util.HashMap;

import wifiunion.com.notice.BaseFragment;
import wifiunion.com.notice.BasePresenter;
import wifiunion.com.notice.Constants;
import wifiunion.com.notice.DeviceDialogCallBack;
import wifiunion.com.notice.NoticeContact;
import wifiunion.com.notice.R;
import wifiunion.com.notice.adapter.NoticeMainAdapter;
import wifiunion.com.notice.entity.DeviceSelectSth;
import wifiunion.com.notice.entity.NoticeCondition;
import wifiunion.com.notice.entity.NoticeInfoList;
import wifiunion.com.notice.presenter.AddRelevanceNoticeConditionPresenter;
import wifiunion.com.notice.presenter.RelevanceNoticeConditionPresenter;
import wifiunion.com.notice.utils.SharedPreferencesUtils;
import wifiunion.com.notice.widget.DeviceSelectSthDialog;
import wifiunion.com.notice.widget.LoadMoreFooterView;
import wifiunion.com.notice.widget.selectmemberdialog.SelectMemberDialog;

/**
 *
 * 触发条件
 */

public class AddTriggerRelevanceFragment extends BaseFragment implements NoticeContact.RelevanceNoticeConditionView,NoticeContact.AddRelevanceNoticeConditionView, View.OnClickListener {

    private View mMainView;

    private LoadMoreFooterView mLoadMoreFooterView;
    private IRecyclerView mRecyclerView;
    private EditText searchEt;

    private NoticeMainAdapter mAdapter;

    //分组成员
    private TextView addSBDXTv;


    private RelevanceNoticeConditionPresenter mRelevanceNoticeConditionPresenter;

    private AddRelevanceNoticeConditionPresenter mAddRelevanceNoticeConditionPresenter;

    private ArrayList<NoticeInfoList> noticeUserList = new ArrayList<NoticeInfoList>();

    private LinearLayout mGroupLayout, mListHeaderLayout;

    //当前通知的UUid
    private String noticeUuid;

    private int mType = 1;

//    private AddNoticeUserDialog mAddNoticeUserDialog;

    private SelectMemberDialog selectMemberDialog;

    private TextView headDowntv;
    private TextView headUpTv;
    private int pageType;

    private ImageView ovalcftjIv;


    private NoticeInfoList mNoticeInfoList;


    private RelativeLayout dataRl;

    private RadioGroup soudRG;
    private RadioButton systemdefRB;
    private RadioButton selfRB;
    private int backgrudtype;
    private EditText peroidEdt;

    private TextView peroidTypeTv;

    /**
     * 访问时间
     */
    private ArrayList<DeviceSelectSth> vistorPeroidTypeList = new ArrayList<>();

    /**
     * 选择对话框
     */
    private DeviceSelectSthDialog deviceSelectDialog;

    /**
     * 访问时限类型
     */
    private int vistorPeroidType = 0;

    private TextView mLessthanTv;

    /**
     *
     * 访问时间类型选择回调
     */
    private DeviceDialogCallBack peroidtypeCallback = new DeviceDialogCallBack() {
        @Override
        public void updateList(ArrayList<DeviceSelectSth> datalist) {

            for (DeviceSelectSth d : datalist) {
                if (d.isSelected()) {
                    peroidTypeTv.setText(d.getName());
                    vistorPeroidType = Integer.parseInt(d.getUuid());
                }
            }
        }
    };


    RadioGroup.OnCheckedChangeListener soudlistener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup Group, int checkedId) {

            if (checkedId == systemdefRB.getId()) {

                backgrudtype = 0;


            } else if (checkedId == selfRB.getId()) {
                backgrudtype = 1;


            }


        }
    };
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mMainView = inflater.inflate(R.layout.fragment_addtriggerrelevancefragment, container, false);
        mRelevanceNoticeConditionPresenter = new RelevanceNoticeConditionPresenter(getContext(), this);
        mAddRelevanceNoticeConditionPresenter = new AddRelevanceNoticeConditionPresenter(getContext(), this);
        Bundle bundle = getArguments();
        if (null != bundle) {
            pageType = bundle.getInt("pageType");
            if (pageType == 0) {
                mNoticeInfoList = (NoticeInfoList) bundle.getSerializable("notice");
                noticeUuid = mNoticeInfoList.getUuid();


            }
        }

        initview();

        return mMainView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();

    }

    @Override
    public void onResume() {
        super.onResume();
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                    getFragmentManager().popBackStack();
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void initview() {

        ovalcftjIv = (ImageView) mMainView.findViewById(R.id.oval_cftj_iv);
        ovalcftjIv.setBackgroundResource(R.drawable.notice_mark_material_select);

//        guideRl = (RelativeLayout) mMainView.findViewById(R.id.notice_guide_rl);
        dataRl = (RelativeLayout) mMainView.findViewById(R.id.notice_data_rl);

        if (pageType == 0) {
//            boolean isguide = SharedPreferencesUtils.getBooleanSharedPreferences(
//                    "noticeguide", getActivity());
//            if (!isguide) {
//                guideRl.setVisibility(View.VISIBLE);
//                dataRl.setVisibility(View.GONE);
//            } else {
//                guideRl.setVisibility(View.GONE);
                dataRl.setVisibility(View.VISIBLE);
//            }
        }


//        bottonRl = (RelativeLayout) mMainView.findViewById(R.id.botton_rl);
//        bottonRl.setOnClickListener(this);

//        mListHeaderLayout = (LinearLayout) mMainView.findViewById(R.id.list_noticelistheader);
//        mRecyclerView = (IRecyclerView) mMainView.findViewById(R.id.notice_irecyclerView);
//        addSBDXTv = (TextView) mMainView.findViewById(R.id.group_add_tv);
//        addSBDXTv.setText("添加识别对象");
//        addSBDXTv.setVisibility(View.VISIBLE);
//        addSBDXTv.setOnClickListener(this);
//        if (pageType == 0 || pageType == 2) {
//            addSBDXTv.setEnabled(true);
//        } else {
//            addSBDXTv.setEnabled(false);
//        }
//
//        filterLayout2 = (LinearLayout) mMainView.findViewById(R.id.sub_header_filter_layout2);
//        filterLayout2.setVisibility(View.GONE);
//
//        groupDelTv = (TextView) mMainView.findViewById(R.id.group_del_tv);
//        groupDelTv.setVisibility(View.GONE);
//
//        searchBtn = (Button) mMainView.findViewById(R.id.search_btn);
//        searchBtn.setOnClickListener(this);
//        searchBtn.setVisibility(View.GONE);


        headDowntv = (TextView) mMainView.findViewById(R.id.notice_head_down_tv);
        headDowntv.setText("保存");
        headDowntv.setOnClickListener(this);
        headUpTv = (TextView) mMainView.findViewById(R.id.notice_head_up_tv);
        headUpTv.setOnClickListener(this);
        soudRG = (RadioGroup) mMainView.findViewById(R.id.backgroud_type_rg);
        systemdefRB = (RadioButton) mMainView.findViewById(R.id.system_def);
        selfRB = (RadioButton) mMainView.findViewById(R.id.self);
        soudRG.setOnCheckedChangeListener(soudlistener);

        peroidEdt = (EditText) mMainView.findViewById(R.id.callin_peroid_edt);
        peroidEdt.addTextChangedListener(new TextWatcher(){

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

               if(s.toString().startsWith("0"))
               {
                   peroidEdt.setText("1");
                   peroidEdt.setSelection(peroidEdt.getText().toString().length());
               }

            }
        });
        peroidTypeTv = (TextView) mMainView.findViewById(R.id.callin_peroid_tv);
        peroidTypeTv.setOnClickListener(this);


        mLessthanTv = (TextView) mMainView.findViewById(R.id.lessthan_tv);
        mLessthanTv.setText("<");


        mMainView.findViewById(R.id.back).setOnClickListener(this);
    }

    public void initData() {
        if (!TextUtils.isEmpty(noticeUuid)) {
            getRelevanceConditionRequest();

        }

    }




    public void getRelevanceConditionRequest() {
        String authtoken = SharedPreferencesUtils.getSharedPreferences(
                Constants.CONFIG_AUTHTOKEN, getContext());
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("Authorization", authtoken);
        params.put("uuid", noticeUuid);


        mRelevanceNoticeConditionPresenter.getRelevanceNoticeCondition(params);
    }

    public void addRelevanceConditionRequest() {
        String authtoken = SharedPreferencesUtils.getSharedPreferences(
                Constants.CONFIG_AUTHTOKEN, getContext());
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("Authorization", authtoken);
        params.put("uuid", noticeUuid);
        if(backgrudtype == 0)
        {
            params.put("intervalTime", 0);
            params.put("intervalTimeType", 0);
        }else if(backgrudtype == 1)
        {
            params.put("intervalTime",Integer.parseInt(peroidEdt.getText().toString()));
            params.put("intervalTimeType", vistorPeroidType);
        }

        mAddRelevanceNoticeConditionPresenter.addRelevanceNoticeCondition(params);
    }



    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.group_add_tv) {
            if (noticeUuid == null) {
                noticeUuid = "0";
            }
        } else if (i == R.id.notice_head_up_tv) {
            getFragmentManager().popBackStack();

        } else if (i == R.id.notice_head_down_tv) {

            addRelevanceConditionRequest();

        } else if (i == R.id.botton_rl) {


        } else if (i == R.id.back) {
            getFragmentManager().popBackStack();

        }else if (i == R.id.callin_peroid_tv) {
            showTimePeroidTypeDialog();
        }

    }

    /**
     * 访问时间类型对话框
     */
    private void showTimePeroidTypeDialog() {
        vistorPeroidTypeList.clear();
        for (int i = 0; i <= 3; i++) {
            DeviceSelectSth d = new DeviceSelectSth();
            d.setUuid(String.valueOf(i));
            if (i == 0) {
                d.setName("秒");
            }else if (i == 1) {
                d.setName("分钟");
            } else if (i == 2) {
                d.setName("小时");
            } else if (i == 3) {
                d.setName("天");
            }
            d.setSelected(false);
            vistorPeroidTypeList.add(d);
        }
        vistorPeroidTypeList.get(vistorPeroidType).setSelected(true);
        deviceSelectDialog = new DeviceSelectSthDialog(getContext(), vistorPeroidTypeList, peroidtypeCallback);
        deviceSelectDialog.setIsSingleSelect(true);
        deviceSelectDialog.setTitleMsg("选择访问时效");
        deviceSelectDialog.show();
    }



    @Override
    public void setPresenter(BasePresenter tp) {

    }

    @Override
    public void onRelevanceNoticeConditionSuccess(Object data) {
        NoticeCondition con = (NoticeCondition)data;
        if(null != con)
        {
            if(con.getIntervalTime() == 0)
            {
                systemdefRB.setChecked(true);
                backgrudtype = 0;
                peroidEdt.setText("1");
                vistorPeroidType = 0;
                peroidTypeTv.setText("秒");


            }
            if (con.getIntervalTime() != 0){
                //自定义
                selfRB.setChecked(true);
                backgrudtype = 1;

                peroidEdt.setText(TextUtils.isEmpty(String.valueOf(con.getIntervalTime())) ? "1" : String.valueOf(con.getIntervalTime()));
                peroidEdt.setSelection(peroidEdt.getText().toString().length());
                try {
                    vistorPeroidType = con.getIntervalTimeType();
                } catch (Exception e) {
                    e.printStackTrace();
                    vistorPeroidType = 0;
                }
                if (vistorPeroidType == 0) {
                    peroidTypeTv.setText("秒");
                }
                 else if (vistorPeroidType == 1) {
                    peroidTypeTv.setText("分钟");
                } else if (vistorPeroidType == 2) {
                    peroidTypeTv.setText("小时");
                } else if (vistorPeroidType == 3) {
                    peroidTypeTv.setText("天");
                }

            }



        }else
        {
            systemdefRB.setChecked(true);
            backgrudtype = 0;

        }

    }

    @Override
    public void onRelevanceNoticeConditionFailed(Object object) {

    }

    @Override
    public void addRelevanceNoticeConditionSuccess(Object data) {

        NoticeListFragment noticeListFragment = (NoticeListFragment) getActivity().getSupportFragmentManager().findFragmentByTag("noticeListFragment");
        if(noticeListFragment==null)
        {
            noticeListFragment = new NoticeListFragment();
        }
        getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.reight_fl, noticeListFragment, "noticeListFragment").addToBackStack(null).commit();

    }

    @Override
    public void addRelevanceNoticeConditionFailed(Object object) {

    }
}








